<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="编号" prop="code">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入编号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="主体" prop="orgname">
        <el-input
          v-model="queryParams.orgname"
          placeholder="请输入主体"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="物流公司" prop="customername">
        <el-input
          v-model="queryParams.customername"
          placeholder="请输入物流公司"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="业务单号" prop="linkcode">
        <el-input
          v-model="queryParams.linkcode"
          placeholder="请输入业务单号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="结算方式" prop="faretype">
        <el-select v-model="queryParams.faretype" placeholder="请选择结算方式" clearable size="small">
          <el-option
            v-for="dict in faretypeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" size="small">
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="parseInt(dict.dictValue)"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="primary"-->
<!--          icon="el-icon-plus"-->
<!--          size="mini"-->
<!--          @click="handleAdd"-->
<!--          v-hasPermi="['wlinfo:wlinfo:add']"-->
<!--        >新增</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="success"-->
<!--          icon="el-icon-edit"-->
<!--          size="mini"-->
<!--          :disabled="single"-->
<!--          @click="handleUpdate"-->
<!--          v-hasPermi="['wlinfo:wlinfo:edit']"-->
<!--        >修改</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="danger"-->
<!--          icon="el-icon-delete"-->
<!--          size="mini"-->
<!--          :disabled="multiple"-->
<!--          @click="handleDelete"-->
<!--          v-hasPermi="['wlinfo:wlinfo:remove']"-->
<!--        >删除</el-button>-->
<!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['wlinfo:wlinfo:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="wlinfoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="code" />
      <el-table-column label="主体" align="center" prop="orgname" />
      <el-table-column label="物流公司" align="center" prop="customername" />
      <el-table-column label="车牌号" align="center" prop="carcode" />
      <el-table-column label="运价" align="center" prop="fareprice" >
        <template slot-scope="scope">
          <span>{{ takePriceUnit(scope.row.fareprice, scope.row.farepricetype) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="重量(吨)" align="center" prop="fareweight" />
      <el-table-column label="金额(元)" align="center" prop="amount" />
      <el-table-column label="业务单号" align="center" prop="" width="100" >
        <template slot-scope="scope">
          <span>{{ takeLinkcode(scope.row.items) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作人" align="center" prop="operator" />
      <el-table-column label="创建时间" align="center" prop="createtime" >
<!--        <template slot-scope="scope">-->
<!--          <span>{{ scope.row.createtime. }}</span>-->
<!--        </template>-->
      </el-table-column>
      <el-table-column label="付款状态" align="center" prop="payStatusName" />
      <el-table-column label="状态" align="center" prop="statusName" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-if="(scope.row.status == 5 || scope.row.status == 15) && permission.includes(9)"
          >修改</el-button>
<!--          <el-button-->
<!--            size="mini"-->
<!--            type="text"-->
<!--            icon="el-icon-edit"-->
<!--            @click="handleDeliver(scope.row)"-->
<!--            v-if="scope.row.status == 5 && permission.includes(9)"-->
<!--          >发货</el-button>-->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-finished"
            @click="handleSettle(scope.row)"
          >结算</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改物流信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" :inline="true" label-width="120px">
        <el-form-item label="主体" prop="freightclaim">
          <el-input v-model="form.orgname" disabled clearable />
        </el-form-item>
        <el-form-item label="物流公司" prop="customername">
          <el-input v-model="form.customername" disabled clearable />
        </el-form-item>
        <el-form-item label="车牌号" prop="carcode">
          <el-input v-model="form.carcode" disabled clearable />
        </el-form-item>
        <el-form-item label="运价" prop="fareprice">
          <el-input v-model="form.fareprice" disabled clearable />
        </el-form-item>
        <el-form-item label="计价方式" prop="farepricetype">
          <el-input v-model="form.farepricetypename" disabled clearable />
        </el-form-item>
        <el-form-item label="运费结算重量" prop="fareweight">
          <el-input v-model="form.fareweight" disabled clearable />
        </el-form-item>
        <el-form-item label="总运费" prop="amount">
          <el-input v-model="form.amount" disabled clearable />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option
              v-for="dict in editStatusOp"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="parseInt(dict.dictValue)"
              :disabled="dict.disabled"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 结算对话框 -->
    <el-dialog :title="title" :visible.sync="open2" width="800px" append-to-body>
      <el-form ref="form2" :model="form" :rules="rules2" :inline="true" label-width="120px">
        <el-form-item label="主体" prop="orgid">
            <el-select v-model="form.orgname" clearable  placeholder="请选择结算主体" :disabled="orgs.length <= 0">
              <el-option
                v-for="dict in orgs"
                :label="dict.name"
                :key="dict.id"
                :value="dict.name"
              ></el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="业务单号">
          <el-input :value="takeLinkcode(form.items)" type="text" disabled clearable />
        </el-form-item>
        <el-form-item label="物流公司" prop="customername">
          <el-select v-model="form.customername" clearable  placeholder="请选择物流公司" style="width: 543px;">
            <el-option
              v-for="dict in suppliers"
              :label="dict.name"
              :key="dict.id"
              :value="dict.name"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="单价" prop="fareprice" style="width: 326px;">
          <el-input v-model="form.fareprice" type="number" placeholder="请输入单价" clearable style="width: 126px;" />
          <el-select v-model="form.farepricetype" placeholder="请选择计价方式" style="width: 80px;">
            <el-option
              v-for="dict in farepricetypeOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="parseInt(dict.dictValue)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="结算重量(吨)" prop="fareweight">
          <el-input v-model="form.fareweight" type="number" placeholder="请输入运费结算重量" clearable />
        </el-form-item>
        <el-form-item label="运费(元)" prop="amount">
          <el-input v-model="form.fareamount" type="number" clearable  readonly />
        </el-form-item>
        <el-form-item label="其他费用(元)" prop="othercost">
          <el-input v-model="form.othercost" type="number" placeholder="请输入其他费用" clearable />
        </el-form-item>
        <el-form-item label="结算金额(元)" prop="amount">
          <el-input v-model="form.amount" type="number" clearable  readonly />
        </el-form-item>
        <el-form-item label="结算方式" prop="faretype">
          <el-select v-model="form.faretype" placeholder="请选择结算方式" clearable>
            <el-option
              v-for="dict in faretypeOptions"
              :label="dict.dictLabel"
              :key="dict.dictValue"
              :value="parseInt(dict.dictValue)"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="otherremark">
          <el-input v-model="form.otherremark" type="textarea" placeholder="请输入备注(如：其他费用说明)" style="width: 208px;" />
        </el-form-item>
<!--        <el-form-item label="状态" prop="status">-->
<!--          <el-input :value="form.statusname" type="text" disabled clearable />-->
<!--        </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :disabled="!([5,15,30].includes(form.status) && permission.includes(9))" @click="submitForm2">确 定</el-button>
        <el-button @click="cancel2">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { listWlinfo, getWlinfo, delWlinfo, addWlinfo, updateWlinfo, exportWlinfo, deliverWlinfo, settleWlinfo, checkOrder  } from "@/api/wlinfo/wlinfo";
  import { getCurrPermis, findOrganizationList } from "@/api/public";
  import { getWlComp } from "@/api/organization/supplier";

  export default {
    name: "Wlinfo",
    components: {
    },
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 物流信息表格数据
        wlinfoList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 结算方式字典
        faretypeOptions: [],
        // 计价方式字典
        farepricetypeOptions: [],
        // 类型字典
        typeOptions: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          code: null,
          customername: null,
          faretype: null,
          fareprice: null,
          farepricetype: null,
          status: null,
          amount: null,
          fareweight: null,
          createtime: null,
          lastupdate: null,
          approvalflag: null,
          containerno: null,
          deliport: null,
          arriport: null,
          othercost: null,
          otherremark: null,
          deductamount: null,
          deductremark: null,
          orgid: null,
          functiontype: 18,
          linkcode: ''
        },
        // 表单参数
        form: {
          othercost: '',
          otherremark: ''
        },
        // 表单校验
        rules: {
          code: [
            { required: true, message: "业务编号不能为空", trigger: "blur" }
          ]
        },
        // 表单校验
        rules2: {
          customername: [{
            required: true,
            message: '请选择物流公司',
            trigger: 'change',
          }, ],
          fareprice: [{
            required: true,
            message: '请选择计价方式',
            trigger: 'change',
          }, ],
          fareweight: [{
            required: true,
            message: '请输入结算重量',
            trigger: 'blur',
          }, ],
          otherremark: [{
            validator: (rule, value, callback) => {
              if (this.form.othercost && !value) {
                callback(new Error('请填写其他费用说明'));
              } else {
                callback();
              }
            },
            trigger: 'blur',
          }, ],
          faretype: [{
            required: true,
            message: '请选择结算方式',
            trigger: 'change',
          }, ],
        },
        permission: [],
        statusOptions: [],
        editStatusOp: [],
        open2: false,
        currOrg: {},
        currCust: {},
        orgs: [],
        suppliers: []
      };
    },
    created() {
      this.getList();
      this.getPermis();
      this.getDicts("wlinfo_fare_type").then(response => {
        this.faretypeOptions = response.data;
      });
      this.getDicts("wlinfo_fare_price_type").then(response => {
        this.farepricetypeOptions = response.data;
      });
      this.getDicts("wlinfo_type").then(response => {
        this.typeOptions = response.data;
      });
      this.getDicts("wlinfo_status").then(response => {
        this.statusOptions = response.data;
      });
    },
    watch: {
      'form.orgname': function(val) {
        if (!val || this.orgs.length <= 0) return;
        let currOrg = this.orgs.filter(item => {
          return item.name == val;
        })[0];
        this.form.orgid = currOrg.id;
      },
      'form.customername': function(val) {
        if (!val || this.suppliers.length <= 0) return;
        let currSup = this.suppliers.filter(item => {
          return item.name == val;
        })[0];
        this.form.customerid = currSup.id;
      },
      'form.farepricetype': function(val) {
        this.computAmount();
      },
      'form.fareprice': function(val) {
        this.computAmount();
      },
      'form.fareweight': function(val) {
        this.computAmount();
      },
      'form.othercost': function(val) {
        this.computAmount();
      }
    },
    methods: {
      computAmount() {
        if (this.form.farepricetype == 1) {
          this.form.fareamount = this.toFloat(this.form.fareprice);
          this.form.amount = this.form.fareamount + this.toFloat(this.form.othercost);
        } else if (this.form.farepricetype == 2) {
          this.form.fareamount = this.toFix2(this.toFloat(this.form.fareprice) * this.toFloat(this.form.fareweight))
          this.form.amount = this.form.fareamount + this.toFloat(this.form.othercost);
        }
      },
      //查询组织
      // findOrganizationList(){
      //   findOrganizationList().then(response => {
      //     this.orgs = response.data;
      //   });
      // },
      /** 查询物流公司列表 */
      getSuppliers() {
        getWlComp().then(response => {
          this.suppliers = response.data;
        });
      },
      /** 查询原单据类型 */
      checkOrder(id) {
        checkOrder({guid: id}).then(response => {
          if (response.data.type == 'TF') {
            let data = response.data;
            this.orgs.push({id: data.fromOrgId, name: data.fromOrg});
            this.orgs.push({id: data.toOrgId, name: data.toOrg});
            let currOrg = {id: this.form.orgid,  name: this.form.orgname}
            if (!this.orgs.some(item => { return item.id == this.form.orgid })) {
              this.orgs.push(currOrg);
            }
          }
        });
      },
      takeLinkcode(items) {
        if (!items) return;
        let txt = '';
        items.forEach((item, index) => {
          if (index == 0) {
            txt = txt.concat(item.linkcode);
          } else {
            txt = txt.concat(',' + item.linkcode);
          }
        })
        return txt;
        // return items.reduce((total, item) => {
        //   return total.concat(item.linkcode);
        // });
      },
      takePriceUnit(price, fptype) {
        let txt = price;
        if (fptype == 1) {
          txt = txt + '元/车';
        } else if (fptype == 2) {
          txt = txt + '元/吨';
        }
        return txt;
      },
      /** 查询物流信息列表 */
      getList() {
        this.loading = true;
        listWlinfo(this.queryParams).then(response => {
          this.wlinfoList = response.rows;
          console.log('this.wlinfoList:', this.wlinfoList)
          this.total = response.total;
          this.loading = false;
        });
      },
      getPermis() {
        getCurrPermis().then(response => {
          this.permission = response.data;
          console.log('this.permission:', this.permission)
        });
      },
      // 结算方式字典翻译
      faretypeFormat(row, column) {
        return this.selectDictLabel(this.faretypeOptions, row.faretype);
      },
      // 计价方式字典翻译
      farepricetypeFormat(row, column) {
        return this.selectDictLabel(this.farepricetypeOptions, row.farepricetype);
      },
      // 类型字典翻译
      typeFormat(row, column) {
        return this.selectDictLabel(this.typeOptions, row.type);
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 取消按钮
      cancel2() {
        this.open2 = false;
        this.orgs = [];
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          guid: null,
          code: null,
          wlguid: null,
          wlcode: null,
          customerid: null,
          customername: null,
          freightclaim: null,
          faretype: null,
          deliprovince: null,
          delicity: null,
          delidistrict: null,
          deliaddress: null,
          arriprovince: null,
          arricity: null,
          arridistrict: null,
          arriaddres: null,
          drivername: null,
          driverphone: null,
          carcode: null,
          delicontact: null,
          delicontacttel: null,
          arricontact: null,
          arricontactno: null,
          senddate: null,
          arrivedate: null,
          loadtime: null,
          unloadtime: null,
          fareprice: null,
          farepricetype: null,
          status: 0,
          amount: null,
          fareweight: null,
          type: null,
          operatorid: null,
          operator: null,
          createtime: null,
          lastupdate: null,
          approvalflag: null,
          containerno: null,
          deliport: null,
          arriport: null,
          othercost: null,
          otherremark: null,
          deductamount: null,
          deductremark: null,
          befdeductamount: null,
          transtype: null,
          flowid: null,
          relatedid: null,
          departid: null,
          departname: null,
          environment: null,
          lifttype: null,
          arriportcountry: null,
          transclause: null,
          remark: null,
          shipcompany: null,
          shipname: null,
          shipcode: null,
          liftcode: null,
          boxtype: null,
          boxsize: null,
          boxcode: null,
          delifactory: null,
          cargodate: null,
          cartype: null,
          mainidsea: null,
          kdcode: null,
          sort: null,
          hook: null,
          orgid: null,
          orgname: null,
          paystatus: null
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.guid)
        this.single = selection.length!==1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加物流信息";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const guid = row.guid || this.ids
        getWlinfo(guid).then(response => {
          this.form = response.data;
          this.editStatusOp = this.statusOptions.map(item => {
            if (this.form.status == 5) {
              if (item.dictValue == 5 || item.dictValue == 15) {
                item.disabled = false;
              } else {
                item.disabled = true;
              }
            } else if (this.form.status == 15) {
              if (item.dictValue == 5 || item.dictValue == 15) {
                item.disabled = false;
              } else {
                item.disabled = true;
              }
            }
            return item;
          })
          this.open = true;
          this.title = "修改物流信息";
        });
      },
      /** 发货按钮操作 */
      handleDeliver(row) {
        const guid = row.guid;
        console.log('guid:', guid)
        deliverWlinfo({guid: guid}).then(response => {
          this.msgSuccess("操作成功");
          this.getList();
        });
      },
      /** 结算按钮操作 */
      handleSettle(row) {
        this.reset();
        const guid = row.guid || this.ids
        getWlinfo(guid).then(response => {
          this.reset();
          this.form = response.data;
          this.checkOrder(this.form.guid);
          this.getSuppliers();
          this.open2 = true;
          this.title = `物流订单结算(编号：${this.form.code})`;
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
              updateWlinfo(this.form).then(response => {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
          }
        });
      },
      /** 提交按钮 */
      submitForm2() {
        this.$refs["form2"].validate(valid => {
          if (valid) {
            settleWlinfo(this.form).then(response => {
              this.msgSuccess("结算成功");
              this.open2 = false;
              this.orgs = [];
              this.getList();
            });
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const guids = row.guid || this.ids;
        this.$confirm('是否确认删除该数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delWlinfo(guids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
      },
      /** 导出按钮操作 */
      handleExport() {
        const queryParams = this.queryParams;
        this.$confirm('是否确认导出所有物流信息数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportWlinfo(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
      }
    }
  };
</script>
